//
//  ChangeCardPhoneViewController.m
//  ZYZB
//
//  Created by ENERGY on 2018/8/23.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "ChangeCardPhoneViewController.h"

@interface ChangeCardPhoneViewController ()
@property (nonatomic, strong)UIWebView * webView;
@property (strong, nonatomic) NSTimer *timer;
@end
@implementation ChangeCardPhoneViewController(networking)
//修改手机号
- (void)changePhoneNumData{
//    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"merOrderNo":self.bankNeedInfoDic[@"merOrderNo"],
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"merOrderNo":self.bankNeedInfoDic[@"merOrderNo"],
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/lunxun/lunxun"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            if ([[jsonData[@"body"] objectForKey:@"code"] isEqualToString:@"000000"]) {
                [self.timer invalidate];
                self.timer = nil;
                [self.navigationController popToRootViewControllerAnimated:YES];
                [self.timer setFireDate:[NSDate distantFuture]];
                NSLog(@"成功");
            }else{
                NSLog(@"未成功");
            }
        }
    }];
}
@end
@implementation ChangeCardPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"修改银行卡预留手机号";
    [self.view addSubview:self.webView];
    
    [self testOpenAccountState];//测试开户成功状态
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.timer invalidate];
    self.timer = nil;
}
- (void)testOpenAccountState{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timered:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}

- (UIWebView *)webView{
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT - BOTTOM_HEIGHT)];
        [_webView loadRequest:[self openUrlWithPostMethod:self.webURLStr params:self.bankNeedInfoDic withSessionID:self.sessionID]];
    }return _webView;
}
//POST方法编码URL和参数
- (NSMutableURLRequest *)openUrlWithPostMethod:(NSString*)url params:(NSDictionary*)params withSessionID:(NSString *)sessionID{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.HTTPMethod = @"POST";
    NSMutableString *paramStr = [NSMutableString string];
    [params enumerateKeysAndObjectsUsingBlock:^( id key , id value , BOOL *stop ) {
        
        if( paramStr.length > 0 ){
            [paramStr appendString:@"&"];
        }
        if ([key isEqualToString:@"url"]) {
            
        }else
            [paramStr appendFormat:@"%@=%@",[self encodeString:key],[self encodeString:value]];
        *stop = NO;
    }];
    [request setValue:sessionID forHTTPHeaderField:@"JSESSIONID"];
    NSLog(@"%@  params ==== %@",request.URL,params);
    request.HTTPBody = [paramStr dataUsingEncoding:NSUTF8StringEncoding];
    
    return request;
}
- (NSString*)encodeString:(NSString*)unencodedString{
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}
#pragma mark - action
- (void)timered:(NSTimer*)timer{
    NSLog(@"timer called");
    [self changePhoneNumData];//判断状态
}


@end
